﻿var viewModel = viewModel || {};
viewModel.basCompany = viewModel.basCompany || {};

viewModel.basCompany.edit = function (data) {
    var me = this;
    me.idField = data.idField;
    me.form = ko.mapping.fromJS(data.form || data.defaultData.formMaster);
    me.resx = data.resx;
    me.setting = data.setting;
    me.dataSource = data.dataSource;
    me.urls = data.urls;
    me.httpMethod = data.form ? "PUT" : "POST";
    delete me.form.__ko_mapping__;



    me.gridDep = {
        pagination: false,
        remotesort: false,
        url: ko.observable(me.urls.queryDep + me.form[me.idField].apply()),
        readonlyFieldsInEdit: me.setting.readonlyFieldsInEditOfDep
    };

    me.editGridDep = new com.editGridViewModel(me.gridDep);
    me.gridDep.onDblClickRow = me.editGridDep.begin;
    me.gridDep.onClickRow = me.editGridDep.ended;

    me.gridDep.toolbar = [{
        text: 'Add',
        iconCls: 'icon-add',
        handler: function () {
            me.editGridDep.addRow(data.defaultData.rowDep);
        }
    }, '-',
        {
            text: 'Delete',
            iconCls: 'icon-delete',
            handler: function () {
                me.editGridDep.deleteRow();
            }
        }];

    me.save = function () {
        var master = ko.toJS(me.form);
        if (!me.editGridDep.ended()) {
            com.message("warning", "Exist invalid data in department detail grid!");
            return false;
        }

        var depChanges = me.editGridDep.getChanges();
        var post = { master: master, detail: [$.extend({ name: 'dep' }, depChanges)] };
        com.ajax({
            type: me.httpMethod,
            url: me.urls.edit,
            data: ko.toJSON(post),
            success: function (d) {
                if (d) {
                    com.message("success", me.resx.saveSuccess);
                }
            }
        });

    };
    me.audit = function () {
    };
}